<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class News extends ActiveRecord
{
	static function getIndexNewsList($where){
		return static::find()->select(['title','catid','slug','describe','news_time','author_id','read_num','status'])->where($where)->andWhere(['status'=>2])->orderBy(['sn'=>SORT_DESC,'id'=>SORT_DESC])->asArray()->limit(10)->all();
	}
	function getNewsList($perCount,$status=0){
		//$page->limit 指一个对象（类）的一个属性；
		$slug = Yii::$app->request->get('catSlug');
		$page = Yii::$app->request->get('page');
		if($slug){
			$cid = findSnFromSlug($slug,'cat_name');
		}
		// var_dump($cid);
		if($cid == -1){
			return null;
		}
		$data = static::find()
				->select(['id','title','news_time','catid','slug','author_id','describe'])
				->where(isset($cid)?['catid'=>$cid]:'')
				->andwhere(['>','status',$status])
				->limit($perCount)
				->orderBy(['id'=>SORT_DESC])
				->offset($perCount * ($page-1) )
				->asArray()
				->all();
				// ->createCommand();
		// var_dump($data->sql);
		// exit;
		return $data;

	}
	function getNewsListCount($status=0){
		$slug = Yii::$app->request->get('catSlug');
		$cid = -1;
		if($slug){
			$cid = findSnFromSlug($slug,'cat_name');
		}
		$where = ($cid!=-1)?['catid'=>$cid]:'';
		$data = static::find()->where(['>','status',$status])->andWhere($where)->count();
		return $data;
	}
	function getNewsContent($catSlug,$slug){
		return $data = static::find()->where(['catid'=>findSnFromSlug($catSlug,'cat_name'),'slug'=>$slug])->andwhere(['>','status',0])->one();
	}
	function createNews(){
		$p = Yii::$app->request->post();
		$News = new News();
		$News->title = $p['title'];
		$News->describe = $p['describe'];
		$News->slug = $p['slug'];
		$News->catid = $p['cid'];
		$News->author_id = $p['author_id'];
		$News->hot = $p['hot']?1:0;
		$News->allow_comment = $p['pl']?1:0;
		$News->sn = $p['sn']?$p['sn']:0;
		$News->status = $p['status'];

		$News->news_time = time();//发布时间
		$News->modify_time = time();//最后修改时间，时间即为最新
		$News->save();
		return  $News->primaryKey;//YII方法，返回最后插入的主键(ID)
	}
	function deleNews($id){
		$News = static::findOne($id);
		return $News->delete();
	}
	function editNews($News){
		$p = Yii::$app->request->post();
		$News->title = $p['title'];
		$News->describe = $p['describe'];
		$News->status = $p['status'];
		$News->slug = $p['slug'];
		$News->catid = $p['cid'];
		$News->author_id = $p['author_id'];
		$News->hot = $p['hot']?1:0;
		$News->allow_comment = $p['pl']?1:0;
		$News->sn = $p['sn']?$p['sn']:0;

		$News->modify_time = time();
		return $News->save();
		
	}
	function getAuthorArticle(){
		
	}
}